﻿using System;
using System.Web;
using System.Collections.Specialized;
using System.Net;
using System.IO;
using System.Text;

namespace SmApiLibrary.libs
{
    [Serializable]
    public class OAuthSohu : OAuthBase
    {
        public OAuthSohu()
        {
            Title = @"搜狐微博";
            //LinkIconUrl = @"http://open.t.sohu.com/upload/connect_button-04134430.png";
            //ConsumerKey = "up1cepg6Lfi8ix1qkKj4";
            //ConsumerSecret = "VSgsP=vRno-3AvAYFvX-A(#zHZozCRdV!cFp#hyv";
            OauthCallback = "null";
            RequestToken = "http://api.t.sohu.com/oauth/request_token";
            Authorize = "http://api.t.sohu.com/oauth/authorize";//?hd=default";
            AccessToken = "http://api.t.sohu.com/oauth/access_token";
        }

        protected override void MultipartformBody(NameValueCollection qs, byte[] boundarybytes, byte[] boundarybytes1, Stream requestStream, string formdataTemplate)
        {
            requestStream.Write(boundarybytes1, 0, boundarybytes1.Length);
            string key = "status";
            string formitem = string.Format(formdataTemplate, key, Utility.UrlEncode(qs[key]));
            byte[] formitembytes = Encoding.UTF8.GetBytes(formitem);
            requestStream.Write(formitembytes, 0, formitembytes.Length);
            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
        }

        public string XAuthLogin(string username, string password)
        {
            //    OAuthConsumer consumer = new DefaultOAuthConsumer(  
            //    "consumer_key", "consumer_secret");  
            //URL url = new URL("http://api.t.sohu.com/oauth/access_token");  
            string url = AccessToken;
            string postData = string.Format("x_auth_username={0}&x_auth_password={1}&x_auth_mode=client_auth", username, password);
            if (postData.Length > 0)
            {
                NameValueCollection qs = HttpUtility.ParseQueryString(postData);
                postData = "";
                foreach (string key in qs.AllKeys)
                {
                    if (postData.Length > 0)
                    {
                        postData += "&";
                    }
                    qs[key] = HttpUtility.UrlEncode(qs[key]);
                    qs[key] = Utility.UrlEncode(qs[key]);
                    postData += (key + "=" + qs[key]);
                }
                if (url.IndexOf("?") > 0)
                {
                    url += "&";
                }
                else
                {
                    url += "?";
                }
                url += postData;
            }
            Uri uri = new Uri(url);
            //HttpURLConnection request = (HttpURLConnection) url.openConnection();  
            //request.setDoOutput(true);  
            //request.setRequestMethod("POST"); 
            string method = Method.POST.ToString();
            //HttpParameters para = new HttpParameters();  
            //para.put("x_auth_username", "your_passport"); 
            //para.put("x_auth_password", "your_password"); 
            //para.put("x_auth_mode", "client_auth");  
            //consumer.setAdditionalParameters(para);  
            //consumer.sign(request); 
            string outUrl;
            string querystring;
            string nonce = GenerateNonce();
            string timeStamp = Utility.GenerateTimeStamp();

            //Generate Signature
            string sig = GenerateSignature(uri,
                                                ConsumerKey,
                                                ConsumerSecret,
                                                Token,
                                                TokenSecret,
                                                Verifier,
                                                method.ToString(),
                                                timeStamp,
                                                nonce,
                                                out outUrl,
                                                out querystring);

            querystring += "&oauth_signature=" + HttpUtility.UrlEncode(sig);

            //postData = querystring;
            //querystring = "";

            var webRequest = System.Net.WebRequest.Create(outUrl) as HttpWebRequest;
            if (webRequest == null) return string.Empty;
            webRequest.Method = method;
            webRequest.ServicePoint.Expect100Continue = false;
            webRequest.UserAgent = "WinWeiBee";
            webRequest.Timeout = 20000;
            webRequest.KeepAlive = true;

            //OutputStream ot = request.getOutputStream();  
            Stream requestStream = webRequest.GetRequestStream();
            //ot.write(("x_auth_username=your_passport&x_auth_password=your_password&x_auth_mode=client_auth").getBytes()); 
            string postbody = string.Format("x_auth_username={0}&x_auth_password={1}&x_auth_mode=client_auth", username, password);
            webRequest.ContentType = "application/x-www-form-urlencoded";
            StreamWriter requestWriter = new StreamWriter(webRequest.GetRequestStream());
            try
            {
                requestWriter.Write(postbody);
            }
            finally
            {
                requestWriter.Close();
            }
            //byte[] postbodybytes = Encoding.ASCII.GetBytes(postbody);
            //requestStream.Write(postbodybytes,0,postbodybytes.Length);
            ////ot.flush();  
            //requestStream.Close();
            //ot.close();  

            NameValueCollection authqs = HttpUtility.ParseQueryString(querystring);
            var oauthSignaturePattern = "OAuth oauth_nonce=\"{0}\", oauth_signature_method=\"HMAC-SHA1\", oauth_timestamp=\"{1}\", oauth_consumer_key=\"{2}\", oauth_signature=\"{3}\", oauth_version=\"1.0\"";
            var authorizationHeader = string.Format(
                                    System.Globalization.CultureInfo.InvariantCulture,
                                    oauthSignaturePattern,
                                    authqs["oauth_nonce"],
                                    authqs["oauth_timestamp"],
                                    ConsumerKey,
                                    authqs["oauth_signature"]);
            webRequest.Headers.Add("Authorization", authorizationHeader);



            //System.out.println("Sending request..."); 
            //request.connect();  
            //System.out.println("Response: " + request.getResponseCode() + " " 
            //    + request.getResponseMessage());  
            //BufferedReader reader =new BufferedReader(new InputStreamReader(request.getInputStream())); 
            //String b = null;  
            //while((b = reader.readLine())!=null){  
            //    System.out.println(b);  
            //}  
            //request.disconnect();  

            return Utility.WebResponseGet(webRequest);
        }
    }
}
